<template>
  <div class="vehicle-display">
    <!-- 轮播图展示车辆 -->
    <div class="carousel-section">
      <h2 class="section-title">车辆展示</h2>
      <el-carousel :interval="4000" type="card" height="320px">
        <el-carousel-item v-for="vehicle in vehicles" :key="vehicle.id">
          <div class="carousel-item">
            <el-image
                :src="getImageUrl(vehicle.images)"
                fit="cover"
                class="car-image"
                :fallback-src="defaultImage"
                @error="handleImageError(vehicle)" />
            <div class="car-info">
              <h3>{{ vehicle.brand }} {{ vehicle.model }}</h3>
              <p>日租金: ¥{{ vehicle.dailyRent?.toFixed(2) || '0.00' }}</p>
              <p>状态: <span :class="getStatusClass(vehicle.status)">{{ formatStatus(vehicle.status) }}</span></p>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 快捷操作区域 -->
    <div class="quick-actions">
      <div class="action-buttons">
        <el-button type="primary" size="medium" @click="navigateToQuery" class="action-button">
          <el-icon><Search /></el-icon>
          <span>查询</span>
        </el-button>

        <el-button type="success" size="medium" @click="navigateToAdd" class="action-button">
          <el-icon><Plus /></el-icon>
          <span>增添</span>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { useRouter } from "vue-router";
import { carList } from "@/api/car";
import { ElMessage } from "element-plus";
import defaultCarImage from '@/assets/default-car.jpg';
import { useMerchantInfoStore } from '@/stores/merchantInfo'

const merchantStore = useMerchantInfoStore()
const merchantId = merchantStore.merchantInfo?.id || ''

const router = useRouter()
const defaultImage = defaultCarImage;

// 车辆数据
const vehicles = ref([])
const loading = ref(false)

// 获取车辆列表
const fetchCarList = async () => {
  try {
    loading.value = true

    // 获取前10条车辆数据用于轮播展示
    const params = {
      pageNum: 1,
      pageSize: 10,
      merchantId:merchantId
    }

    console.log('请求参数:', params)
    const res = await carList(params)
    console.log('响应数据:', res.data)

    if(res?.code === 200) {
      vehicles.value = res.data?.records || []
      // 如果数据不足3条，添加一些空数据保持轮播效果
      if(vehicles.value.length < 3) {
        const emptyCount = 3 - vehicles.value.length
        for(let i = 0; i < emptyCount; i++) {
          vehicles.value.push({
            id: `empty-${i}`,
            brand: '暂无数据',
            model: '-',
            dailyRent: 0,
            status: 0,
            images: ''
          })
        }
      }
    } else {
      ElMessage.error(res?.message || '获取数据失败')
    }
  } catch(error) {
    console.error('获取车辆列表错误:', error)
    ElMessage.error('获取车辆列表失败')
  } finally {
    loading.value = false
  }
}

// 图片URL处理
const getImageUrl = (filename) => {
  if (!filename) return defaultImage;
  return `/api/file/download.do?filename=${filename}`;
};

// 图片加载失败处理
const handleImageError = (row) => {
  console.error(`图片加载失败: ${row.brand} ${row.model}`)
  // 可以在这里添加错误处理逻辑
}

// 状态格式化
const formatStatus = (status) => {
  switch(status) {
    case 0: return '可租';
    case 1: return '已租出';
    case 2: return '维修中';
    default: return '未知状态';
  }
}

// 状态样式处理
const getStatusClass = (status) => {
  switch(status) {
    case 0: return 'status-available';
    case 1: return 'status-rented';
    case 2: return 'status-maintenance';
    default: return 'status-default';
  }
}

const navigateToQuery = () => {
  router.push('/vehicle-query')
}

const navigateToAdd = () => {
  router.push('/vehicle-add')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCarList()
})

// 定义组件事件
defineEmits(['query', 'add'])
</script>

<style scoped>
.vehicle-display {
  padding: 20px;
}

.section-title {
  margin-bottom: 20px;
  color: #333;
}

.carousel-item {
  position: relative;
  height: 100%;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.car-image {
  width: 100%;
  height: 200px;
}

.car-info {
  padding: 15px;
}

.car-info h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.car-info p {
  margin: 5px 0;
  color: #666;
  font-size: 14px;
}

.status-available {
  color: #67C23A;
}

.status-rented {
  color: #F56C6C;
}

.status-maintenance {
  color: #E6A23C;
}

.status-default {
  color: #909399;
}

.quick-actions {
  margin-top: 30px;
  text-align: center;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.action-button {
  min-width: 120px;
}
</style>